package com.weijian.service.impl;

import com.weijian.common.exception.ErrorCode;
import com.weijian.common.pojo.CommonResult;
import com.weijian.dal.dataobject.Article;
import com.weijian.service.ArticleService;
import com.weijian.service.UploadService;
import com.weijian.utils.ParseWordFileUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class UploadServiceImpl implements UploadService {

    final ArticleService articleService;

    @Override
    public CommonResult<String> parseFiles(List<MultipartFile> files) {

        if (files.get(0).getOriginalFilename().endsWith(".csv"))
            return parseCsvFiles(files);
        return parseWordFiles(files);
    }

    private CommonResult<String> parseWordFiles(List<MultipartFile> files) {
        try {
            if (!ParseWordFileUtil.isValidWordFile(files)) {
                return CommonResult.error(new ErrorCode(400, "上传的文件必须是同类型的，且文件名不能为空"));
            }
            // 2. 解析文件内容
            String filename = files.get(0).getOriginalFilename();
            assert filename != null;
            if (filename.endsWith(".docx")) {
                ParseWordFileUtil.parseDocxFilesAndStore(files, articleService);
            } else if (filename.endsWith(".doc")) {
                ParseWordFileUtil.parseDocFilesAndStore(files, articleService);
            }
            return CommonResult.success("解析成功");
        } catch (Exception e) {
            return CommonResult.error(new ErrorCode(400, "文件有误，解析失败"));
        }
    }

    public CommonResult<String> parseCsvFiles(List<MultipartFile> files) {
        List<Article> allArticles = new ArrayList<>();

        try {
            for (MultipartFile file : files) {
                try (BufferedReader fileReader = new BufferedReader(
                        new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8))) {
                    CSVFormat csvFormat = CSVFormat.DEFAULT.builder()
                            .setHeader()
                            .setSkipHeaderRecord(true)
                            .setIgnoreHeaderCase(true)
                            .setTrim(true)
                            .build();

                    try (CSVParser csvParser = new CSVParser(fileReader, csvFormat)) {
                        List<Article> articles = new ArrayList<>();
                        for (CSVRecord csvRecord : csvParser) {
                            Article article = new Article();
                            article.setTitle(csvRecord.get("title"));
                            article.setParentTagNames(csvRecord.get("parentTagNames"));
                            article.setTagNames(csvRecord.get("tagNames"));
                            article.setDimensionTagNames(csvRecord.get("dimensionTagNames"));
                            article.setContent(csvRecord.get("content"));
                            articles.add(article);
                        }
                        allArticles.addAll(articles);
                    }
                }
            }
            if (!allArticles.isEmpty()) {
                articleService.saveBatch(allArticles);
            }
            return CommonResult.success("解析成功");
        } catch (IOException e) {
            return CommonResult.error(new ErrorCode(400, "文件有误，解析失败"));
        }
    }
}
